//
//  SignUpVC.m
//  SelfDrivingTravelling-IOS
//
//  Created by Teplot_01 on 16/8/3.
//  Copyright © 2016年 Teplot_01. All rights reserved.
//

#import "SignUpVC.h"
#import "AddNewPeopelVC.h"
#import "TouristPersonalInfoVC.h"
#import "SignUpCell.h"
#import "ZZPSDInputView.h"
#import "ZZActionSheet.h"
@interface SignUpVC ()<UITableViewDelegate,UITableViewDataSource>

@end

@implementation SignUpVC
{
    UITableView *_tabelView;
    UITableView *_UpTableView;
    NSMutableArray *_selIndexArr;
    UILabel *_moneyLb;
    UIButton *_signUpBtn;
    UIButton *_triangleBtn;
    
    NSArray *_arr;
    //请求下来的字典
    NSDictionary *_responseDic;
    //请求下来的数组
    NSArray *_responseArr;
    //报名的参数
    NSDictionary *_parameters;
}
- (void)viewWillAppear:(BOOL)animated{
    _arr = [CacheData getArr];
    [_tabelView reloadData];
    NSLog(@"%@",_arr);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = superBackgroundColor;
    self.title = @"活动报名";
    [self requestForSignUpList];
    [self initTableViewWithSignUpList];
    [self initTabelViewWithPeoNum];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(doneAction)];
    _selIndexArr = [[NSMutableArray alloc]init];
}
- (void)initTableViewWithSignUpList{
    _UpTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight/2) style:UITableViewStylePlain];
    _UpTableView.delegate = self;
    _UpTableView.scrollEnabled = NO;
    _UpTableView.dataSource = self;
    _UpTableView.separatorStyle = NO;
//    UIPanGestureRecognizer *tapGest = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestFinger:)];
    UITapGestureRecognizer *tapGest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(panGestFinger:)];
    tapGest.numberOfTapsRequired = 1;
    [_UpTableView addGestureRecognizer:tapGest];
    [self.view addSubview:_UpTableView];
}
- (void)initTabelViewWithPeoNum{
    _tabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, KScreenHeight/2, KScreenWidth, KScreenHeight/2) style:UITableViewStyleGrouped];
    _tabelView.backgroundColor = [UIColor whiteColor];
    _tabelView.scrollEnabled = NO;
    _tabelView.separatorStyle = NO;
    _tabelView.delegate = self;
    _tabelView.dataSource = self;
    [self.view addSubview:_tabelView];
}
#pragma - mark 活动报名人员列表
- (void)requestForSignUpList{
    //参数
    NSDictionary *parameters = @{
                                 @"userId":[NSString readToNSDefaultsWithKey:kId],
                                 @"activityID": self.activityId,
                                 };
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/activity/signUpPersonList.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        _responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@>>>>",_responseDic);
        _responseArr = _responseDic[@"list"];
//        NSString *error = _responseDic[@"code"];
        if (![_responseDic[@"code"] isEqualToString:@"0000"]) {
//            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
            [_UpTableView reloadData];
        }else{
            //请求成功
//            [SVProgressHUD showSuccessWithStatus:@"列表请求成功"];
            [_tabelView reloadData];
            [_UpTableView reloadData];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求失败"];
    }];
}
#pragma - mark UITabelViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:_tabelView]){
        return _arr.count+1;
    }else{
       return _responseArr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SignUpCell *cell = [[NSBundle mainBundle]loadNibNamed:@"SignUpCell" owner:nil options:nil][0];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if ([tableView isEqual:_tabelView]) {
        if (indexPath.row == 0) {
            cell.name.text = [NSString readToNSDefaultsWithKey:kRealName];
            cell.IdCard.text = [NSString readToNSDefaultsWithKey:kCard];
        }else{
            cell.name.text = _arr[indexPath.row-1][@"name"];
            cell.IdCard.text = _arr[indexPath.row-1][@"card"];
        }
        _signUpBtn = [[UIButton alloc]initWithFrame:CGRectMake(KScreenWidth-78, 5, 60, 30)];
        _signUpBtn.tag = indexPath.row;
        _signUpBtn.layer.cornerRadius = 5;
        _signUpBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        _signUpBtn.backgroundColor = Theme_Color;
        [_signUpBtn setTitle:@"报 名" forState:UIControlStateNormal];
        [_signUpBtn addTarget:self action:@selector(signUpBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:_signUpBtn];
    }
    if ([tableView isEqual:_UpTableView]){
        cell.name.text = _responseArr[indexPath.row][@"name"];
        cell.IdCard.text = _responseArr[indexPath.row][@"cardNo"];
        UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(KScreenWidth-73, 5, 60, 30)];
        [cancelBtn setImage:[UIImage imageNamed:@"X"] forState:UIControlStateNormal];
        cancelBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 40, 0, 10);
        [cancelBtn addTarget:self action:@selector(cancelBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:cancelBtn];
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if ([tableView isEqual:_UpTableView]) {
        return 0;
    }
    return 35;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(10, 0, KScreenWidth, 20)];
    if ([tableView isEqual:_tabelView]){
        UIButton *Btn = [[UIButton alloc]initWithFrame:CGRectMake(KScreenWidth/2-100, 0, 200, 35)];
        [Btn setTitle:@"＋  添加联系人" forState:UIControlStateNormal];
        [Btn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [Btn setTitleColor:Black_Color forState:UIControlStateNormal];
        [Btn addTarget:self action:@selector(addPeoAction) forControlEvents:UIControlEventTouchUpInside];
        [customView addSubview:Btn];
        
        UIView *lineV = [[UIView alloc]initWithFrame:CGRectMake(20, 0, KScreenWidth-40, 0.5)];
        lineV.alpha = 0.5;
        lineV.backgroundColor = Theme_Color;
        [customView addSubview:lineV];
    }
    return customView;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(10, 0, KScreenWidth, 50)];
    customView.backgroundColor = White_Color;
    if ([tableView isEqual:_UpTableView]) {
        UIView *garView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 15)];
        garView.backgroundColor = superBackgroundColor;
        [customView addSubview:garView];
        
        UILabel *lb = [[UILabel alloc]initWithFrame:CGRectMake(20, 15, 100, 35)];
        lb.text = @"报名列表";
        lb.textColor = Theme_Color;
        lb.font = [UIFont systemFontOfSize:16];
        [customView addSubview:lb];
        
        UIView *lineV = [[UIView alloc]initWithFrame:CGRectMake(20, 50, KScreenWidth-40, 0.5)];
        lineV.alpha = 0.5;
        lineV.backgroundColor = Theme_Color;
        [customView addSubview:lineV];
        
        UILabel *numLb = [[UILabel alloc]initWithFrame:CGRectMake(KScreenWidth-35, 25, 16, 16)];
        numLb.backgroundColor = Orange_Color;
        numLb.layer.masksToBounds = YES;
        numLb.layer.cornerRadius = 8;
        numLb.text = [NSString stringWithFormat:@"%ld",_responseArr.count];
        numLb.font = [UIFont systemFontOfSize:10];
        numLb.textColor = White_Color;
        numLb.textAlignment = NSTextAlignmentCenter;
        [customView addSubview:numLb];
    }
    if ([tableView isEqual:_tabelView]) {
        UIView *garView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 15)];
        garView.backgroundColor = superBackgroundColor;
        [customView addSubview:garView];
        
        UILabel *lb = [[UILabel alloc]initWithFrame:CGRectMake(20, 15, 100, 35)];
        lb.text = @"联系人列表";
        lb.textColor = Theme_Color;
        lb.font = [UIFont systemFontOfSize:16];
        [customView addSubview:lb];
        
        UIView *lineV = [[UIView alloc]initWithFrame:CGRectMake(20, 50, KScreenWidth-40, 0.5)];
        lineV.alpha = 0.5;
        lineV.backgroundColor = Theme_Color;
        [customView addSubview:lineV];
        
        _triangleBtn = [[UIButton alloc]initWithFrame:CGRectMake(KScreenWidth-200, 15, 200, 35)];
        [_triangleBtn setImage:[UIImage imageNamed:@"triangle"] forState:UIControlStateNormal];
        _triangleBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 150, 0, 10);
        [_triangleBtn addTarget:self action:@selector(triangleBtnActionShouqi) forControlEvents:UIControlEventTouchUpInside];
        [customView addSubview:_triangleBtn];
    }
    return customView;
}
//支付跳转
- (void)payBtnAction{
    //弹出键盘输入密码
    ZZActionSheet *sheet        = [[ZZActionSheet alloc] init];
    sheet.dismissWhenTouchBlank = YES;
    
    ZZPSDInputView *psdView     = [ZZPSDInputView psdInputView];
    psdView.backgroundColor     = [UIColor whiteColor];
    __weak __typeof(sheet) weakSheet = sheet;
    psdView.cancelHandler = ^() {
        [weakSheet dismiss];
    };
    psdView.finishHandler = ^(NSString *passStr) {
        [weakSheet dismissWithCompletion:^{
            //此处判断密码是否正确
            NSLog(@"完成: %@", passStr);
        }];
    };
    
    sheet.contentView = psdView;
    [sheet show];
}
- (void)signUpBtnAction:(UIButton *)sender{
    UITableViewCell * cell = (UITableViewCell *)[[sender superview] superview];
    NSIndexPath * path = [_tabelView indexPathForCell:cell];
    if (path.row == 0) {
        _parameters = @{
                        @"userId":[NSString readToNSDefaultsWithKey:kId],
                        @"userName": @"",
                        @"activityId": self.activityId,
                        @"userPhone":@"",
                        @"cardNo": @"",
                        @"roomCount": @"3",
                        };
        [self requestForSignUp];
    }else{
        _parameters = @{
                        @"userId":@"",
                        @"userName": _arr[path.row-1][@"name"],
                        @"activityId": self.activityId,
                        @"userPhone":_arr[path.row-1][@"phone"],
                        @"cardNo": _arr[path.row-1][@"card"],
                        @"roomCount": @"",
                        };
        [self requestForSignUp];
//        UIButton *button = (UIButton *)[_tabelView viewWithTag:sender.tag];
//        button.enabled = NO;
//        button.backgroundColor = Gray_Color;
    }
}
//取消报名
- (void)cancelBtnAction:(UIButton *)sender{
    UITableViewCell * cell = (UITableViewCell *)[[sender superview] superview];
    NSIndexPath * path = [_UpTableView indexPathForCell:cell];
    //参数
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
    [parameters setValue:_responseArr[path.row][@"id"] forKey:@"userId"];
    [parameters setValue:self.activityId forKey:@"activityId"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/activity/cancelSignUp.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        _responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@>>>>",_responseDic);
        _responseArr = _responseDic[@"list"];
        NSString *error = _responseDic[@"code"];
        if (![_responseDic[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
        }else{
            //请求成功
            [SVProgressHUD showSuccessWithStatus:@"取消报名成功"];
            [self requestForSignUpList];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求失败"];
    }];
}
//确认报名
- (void)requestForSignUp{
        //参数
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer=[AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        [manager POST:@"http://115.28.152.130/tour/v1/activity/signUp.action" parameters:_parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
            NSDictionary *_responseSignDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"%@>>>>",_responseSignDic);
            //  NSArray *_responseArr = _responseDic[@"list"];
            NSString *error = _responseSignDic[@"code"];
            if (![_responseSignDic[@"code"] isEqualToString:@"0000"]) {
                [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
            }else{
                //请求成功
                [SVProgressHUD showSuccessWithStatus:@"活动报名成功"];
                [self requestForSignUpList];
            }
            
        } failure:^(NSURLSessionDataTask *operation, NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"活动报名失败"];
        }];

}
- (void)triangleBtnActionShouqi{
    //选择游客动画效果消失
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    [_tabelView setFrame:CGRectMake(0, KScreenHeight/2, KScreenWidth, 50)];
    [UIView commitAnimations];
    [_triangleBtn removeTarget:self action:@selector(triangleBtnActionShouqi) forControlEvents:UIControlEventTouchUpInside];
    [_triangleBtn addTarget:self action:@selector(triangleBtnActionSpread) forControlEvents:UIControlEventTouchUpInside];
}
- (void)triangleBtnActionSpread{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    [_tabelView setFrame:CGRectMake(0, KScreenHeight/2, KScreenWidth, KScreenHeight/2)];
    [UIView commitAnimations];
    [_triangleBtn removeTarget:self action:@selector(triangleBtnActionSpread) forControlEvents:UIControlEventTouchUpInside];
    [_triangleBtn addTarget:self action:@selector(triangleBtnActionShouqi) forControlEvents:UIControlEventTouchUpInside];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //选择游客动画效果弹出
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    [_tabelView setFrame:CGRectMake(0, KScreenHeight/2, KScreenWidth, KScreenHeight/2)];
    [UIView commitAnimations];
}
- (void)doneAction{
    [[self navigationController] popViewControllerAnimated:YES];
}
//- (void)sureBtnAction{
//    [UIView beginAnimations:nil context:nil];
//    [UIView setAnimationDuration:0.5];
//    [UIView setAnimationDelegate:self];
//    [_tabelView setFrame:CGRectMake(0, KScreenHeight/2, KScreenWidth, 50)];
//    [UIView commitAnimations];
//}
//添加新用户
- (void)addPeoAction{
    AddNewPeopelVC *vc = [[AddNewPeopelVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)panGestFinger:(UITapGestureRecognizer *)sender{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    [_tabelView setFrame:CGRectMake(0, KScreenHeight/2, KScreenWidth, KScreenHeight/2)];
    [UIView commitAnimations];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
